package cn.mickey.cloud.controller;


import cn.mickey.cloud.entity.Comment;
import cn.mickey.cloud.entity.House;
import cn.mickey.cloud.entity.Page;
import cn.mickey.cloud.service.CommentService;
import cn.mickey.cloud.service.HouseService;
import cn.mickey.cloud.utils.FileAction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("house")
public class HouseController {

    @Resource
    private HouseService houseService;
    @Resource
    private FileAction fileAction;
    @Resource
    private CommentService commentService;
    @RequestMapping("find")
    public String findHouseAll(long id, Model model) {
        House one = houseService.getOne(id);
        model.addAttribute("one", one);
        return "front/home_details";
    }

    @ResponseBody
    @RequestMapping("page")
    public Page page(int page, int limit) {
        return houseService.page((page - 1) * limit, limit);
    }

    @ResponseBody
    @RequestMapping("del")
    public String del(Long id) {
        houseService.delList(id);
        return "ok";
    }


    @ResponseBody
    @RequestMapping("delList")
    public String delList(@RequestBody List<Long> ids) {
        houseService.delList(ids);
        return "ok";
    }

    /**
     * 上传图片
     * @param fileImg
     * @param fileArr
     * @param house
     * @return
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("add")
    public String uploadImage(MultipartFile fileImg, MultipartFile[] fileArr, House house) throws IOException {
        //上传宣传图和上传详情图
        houseService.add(fileAction.uploadImage(house,fileImg,fileArr));
        return "ok";
    }

    /**
     * 更新图片
     * @param fileImg
     * @param fileArr
     * @param house
     * @return
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("update")
    public String updateImage(MultipartFile fileImg, MultipartFile[] fileArr, House house) throws IOException {
        //上传图片才更新
        if (fileImg.getSize() != 0 ) {
            fileAction.publicityImg(house, fileImg);
        }
        if(fileArr[0].getSize() != 0){
            fileAction.detailsImg(house,fileArr);
        }
        houseService.update(house);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/issue")
    public String comment(@RequestBody Comment comment){
        //System.out.println(comment);
        commentService.insertOneComment(comment);
        return "ok";
    }
}
